//
//  GetTimestamp.m
//  CarsFiles_QYB
//
//  Created by 程虎 on 2017/4/5.
//  Copyright © 2017年 程虎. All rights reserved.
//

#import "Tools.h"

static Tools *tools;
@implementation Tools

+(Tools *)shareInstance
{
    //加锁
    @synchronized(self)
    {
        if(tools == nil)
        {
            tools = [[[self class] alloc] init];
        }
    }
    return tools;
}

+ (NSString *)getEncryptKey
{
    return @"s(p7~;j^";
}

+ (NSString *)getSigntKey
{
    return @"C*GL_#G_";
}

#pragma mark - 等比例缩放图片
+ (UIImage*)imageCompressWithSimple:(UIImage*)image scale:(float)scale
{
    CGSize size = image.size;
    CGFloat width = size.width;
    CGFloat height = size.height;
    CGFloat scaledWidth = width * scale;
    CGFloat scaledHeight = height * scale;
    UIGraphicsBeginImageContext(size); // this will crop
    [image drawInRect:CGRectMake(0,0,scaledWidth,scaledHeight)];
    UIImage* newImage= UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

#pragma mark - 字符串转数组
+ (NSArray *)toJSONData:(id)jsonData
{
    if (jsonData == nil) {
        return nil;
    }
    NSError *error = nil;
    NSData *nsData = [(NSString*)jsonData dataUsingEncoding:NSUTF8StringEncoding];
    id jsonObject = [NSJSONSerialization JSONObjectWithData:nsData
                                                    options:NSJSONReadingAllowFragments
                                                      error:&error];
    
    
    if (nsData != nil && error == nil){
        return (NSArray *)jsonObject;
    }else{
        // 解析错误
        LSLog(@"解析错误");
        return nil;
    }
}

#pragma mark - 将字典或者数组转化为JSON串
+ (NSString *)toJSONString:(id)theData
{
    NSError *error = nil;
    
    if (theData == nil){
         return nil;
    }else{
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:theData options:NSJSONWritingPrettyPrinted error:nil];
        
        if ([jsonData length] && error == nil){
            NSString *jsonStr=[[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
            return jsonStr;
        }else{
            return nil;
        }
    }
 
}

#pragma mark - leap图片数组转化
+ (NSMutableArray *)leapImgAry:(NSArray *)arrays
{
    if (arrays.count > 0){
        NSMutableArray *arys = [NSMutableArray array];
        if (arrays.count) {
            if ([arrays isKindOfClass:[NSDictionary class]]) {
                return arys;
            }
        }
        for (NSDictionary *dict in arrays) {
            if ([Util getLeapDownLoadUrl:LeapUrl uploadResult:dict] != nil) {
                [arys addObject:[Util getLeapDownLoadUrl:LeapUrl uploadResult:dict]];
            }
        }
        return arys;
    }else{
        return nil;
    }
   
}

#pragma mark - 获取当前时间戳
+ (NSString *)getCurrentDate
{
    NSDate *dates = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
    NSString *currentdate = [formatter stringFromDate:dates];
    return currentdate;
    
   
}
+ (NSString *)stringFromDate:(NSDate *)date
{
    //获取系统当前时间
    NSDate *currentDate = [NSDate date];
    //用于格式化NSDate对象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设置格式：zzz表示时区
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss zzz"];
    //NSDate转NSString
    NSString *currentDateString = [dateFormatter stringFromDate:currentDate];
    //输出currentDateString
    NSLog(@"%@",currentDateString);
    return currentDateString;
}
+ (NSDate *)getInternetDate
{
    NSString *urlString = @"http://m.baidu.com";
    urlString = [urlString stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString: urlString]];
    [request setCachePolicy:NSURLRequestReloadIgnoringCacheData];
    [request setTimeoutInterval: 2];
    [request setHTTPShouldHandleCookies:FALSE];
    [request setHTTPMethod:@"GET"];
    NSHTTPURLResponse *response;
    [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
    
    NSString *date = [[response allHeaderFields] objectForKey:@"Date"];
    date = [date substringFromIndex:5];
    date = [date substringToIndex:[date length]-4];
    NSDateFormatter *dMatter = [[NSDateFormatter alloc] init];
    dMatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
    [dMatter setDateFormat:@"dd MMM yyyy HH:mm:ss"];
    NSDate *netDate = [[dMatter dateFromString:date] dateByAddingTimeInterval:60*60*8];
    
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate: netDate];
    NSDate *localeDate = [netDate  dateByAddingTimeInterval: interval];
    return localeDate;
}
#pragma mark - 正则验证用户名和密码
+ (BOOL)checkUserNameRationality:(NSString *)rationalityString
{
    NSString *pattern = @"^(?![0-9]+$)[A-Z0-9a-z]{6,15}$";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",pattern];
    BOOL isMatch = [predicate evaluateWithObject:rationalityString];
    return isMatch;
}

#pragma mark - 正则验证手机号
+ (BOOL)checkPhoneNORationality:(NSString *)rationalityString
{
    NSString *pattern = @"^[1][0-9]{10}$";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",pattern];
    BOOL isMatch = [predicate evaluateWithObject:rationalityString];
    return isMatch;
}

#pragma mark - 正则验证密码
+ (BOOL)checkPassWordRationality:(NSString *)rationalityString
{
    NSString *pattern = @"^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",pattern];
    BOOL isMatch = [predicate evaluateWithObject:rationalityString];
    return isMatch;
}

#pragma mark - 去掉边框线
+ (UIImage*) createImageWithColor: (UIColor*) color
{
    CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}

#pragma mark - 字符串分解成数组
+ (NSArray *)jsonStringIntoArray:(NSString *)aryStr
{
    NSString *str =  [aryStr stringByReplacingOccurrencesOfString:@" " withString:@""];;
    return [str componentsSeparatedByString:@","];
}

#pragma mark - 计算label的高度
+ (CGFloat )getlabsHeight:(NSString *)strings Font:(CGFloat)font Width:(CGFloat)width
{
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    attrs[NSFontAttributeName] = [UIFont systemFontOfSize:font];
    
    return [strings boundingRectWithSize:CGSizeMake( width,MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size.height;
}

#pragma mark - 计算label的宽度
+ (CGFloat)getlabsWidth:(NSString *)strings Font:(CGFloat)font Height:(CGFloat)height
{
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    attrs[NSFontAttributeName] = [UIFont systemFontOfSize:font];
    
    return [strings boundingRectWithSize:CGSizeMake( MAXFLOAT,height) options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size.width;
}

#pragma mark - 设置label间距
- (NSMutableAttributedString *)setLabelLineSpaceTextString:(NSString *)textString
{
    NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc]initWithString:textString];
    
    NSMutableParagraphStyle *paragraphStyle1 = [[NSMutableParagraphStyle alloc]init];
    [paragraphStyle1 setLineSpacing:3];
    [attributeString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle1 range:NSMakeRange(0, [textString length])];
    
    return attributeString;
}


#pragma mark - 拉伸图片
+ (UIImage *)drawingPicturesWithmargin:(CGFloat )margin images:(NSString *)imgName
{
    UIImage *image = [UIImage imageNamed:@"home_timeBtn"];
    
    CGFloat top = 10; // 顶端盖高度
    CGFloat bottom = 10; // 底端盖高度
    CGFloat left = 10; // 左端盖宽度
    CGFloat right = 10; // 右端盖宽度
    UIEdgeInsets insets = UIEdgeInsetsMake(top, left, bottom, right);
    // 指定为拉伸模式，伸缩后重新赋值
    image = [image resizableImageWithCapInsets:insets resizingMode:UIImageResizingModeStretch];
    return image;
}

#pragma mark - 替换手机号中间四颗星
+ (NSString *)replaceWithMobileNO:(NSString *)mobileStr
{
    if (mobileStr.length != 11) {
        return mobileStr;
    }
    NSString *string = [mobileStr substringWithRange:NSMakeRange(3,4)];
    //字符串的替换
    NSString *mobileString = [mobileStr stringByReplacingOccurrencesOfString:string withString:@"****"];
    return mobileString;
}

#pragma mark 正则表达式
+ (BOOL)MatchLetter:(NSString *)str
{
    //判断是否以字母开头
    NSString *ZIMU = @"^[A-Za-z]+$";
    NSPredicate *regextestA = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", ZIMU];
    
    if ([regextestA evaluateWithObject:str] == YES)
        return YES;
    else
        return NO;
}

#pragma mark - 判断首字符是不是汉字
+ (BOOL)isChineseFirst:(NSString *)firstStr
{
    //是否以中文开头(unicode中文编码范围是0x4e00~0x9fa5)
    int utfCode = 0;
    void *buffer = &utfCode;
    NSRange range = NSMakeRange(0, 1);
    //判断是不是中文开头的,buffer->获取字符的字节数据 maxLength->buffer的最大长度 usedLength->实际写入的长度，不需要的话可以传递NULL encoding->字符编码常数，不同编码方式转换后的字节长是不一样的，这里我用了UTF16 Little-Endian，maxLength为2字节，如果使用Unicode，则需要4字节 options->编码转换的选项，有两个值，分别是NSStringEncodingConversionAllowLossy和NSStringEncodingConversionExternalRepresentation range->获取的字符串中的字符范围,这里设置的第一个字符 remainingRange->建议获取的范围，可以传递NULL
    BOOL b = [firstStr getBytes:buffer maxLength:2 usedLength:NULL encoding:NSUTF16LittleEndianStringEncoding options:NSStringEncodingConversionExternalRepresentation range:range remainingRange:NULL];
    if (b && (utfCode >= 0x4e00 && utfCode <= 0x9fa5))
        return YES;
    else
        return NO;
}

#pragma mark - 将 等类似的字符转化为HTML中的“<”等
+ (NSString *)htmlEntityDecode:(NSString *)string
{
    string = [string stringByReplacingOccurrencesOfString:@"&quot;" withString:@"\""];
    string = [string stringByReplacingOccurrencesOfString:@"&apos;" withString:@"'"];
    string = [string stringByReplacingOccurrencesOfString:@"&lt;" withString:@"<"];
    string = [string stringByReplacingOccurrencesOfString:@"&gt;" withString:@">"];
    string = [string stringByReplacingOccurrencesOfString:@"&amp;" withString:@"&"]; // Do this last so that, e.g. @"&amp;lt;" goes to @"&lt;" not @"<"
    
    return string;
}

#pragma mark - 创建lab
- (UILabel *)creat_Label:(NSString *)texts Color:(UIColor *)colors Font:(CGFloat )fontsize tag:(NSInteger)tags Alignment:(NSInteger )txtAlignment Lines:(NSInteger )lines
{
    UILabel *labels = [UILabel new];
    labels.text = texts;
    labels.backgroundColor = [UIColor clearColor];
    labels.textColor = colors;
    if (tags != -1) {
        labels.tag = tags;
    }
    labels.textAlignment = txtAlignment;
    labels.numberOfLines = lines;
    labels.font = [UIFont systemFontOfSize:fontsize];
    
    return labels;
}

#pragma mark - 创建button
- (UIButton *)creat_Button:(NSString *)titles Color:(UIColor *)colors BackColors:(UIColor *)backColors Font:(CGFloat )fontsize tag:(NSInteger)tags
{
    UIButton *btns = [UIButton buttonWithType:UIButtonTypeCustom];
    btns.adjustsImageWhenHighlighted = NO;
    if (![titles isEqualToString:@""] || titles != nil) {
        [btns setTitle:titles forState:UIControlStateNormal];
    }
    if (colors != nil) {
        [btns setTitleColor:colors forState:UIControlStateNormal];
    }
    if (fontsize != 0) {
        btns.titleLabel.font = [UIFont systemFontOfSize:fontsize];
    }
    if (backColors != nil) {
        btns.backgroundColor = backColors;
    }
    if (tags != -1) {
        btns.tag = tags;
    }
    return btns;
}

+ (UIButton *)creat_Buttons:(NSString *)titles Color:(UIColor *)colors BackColors:(UIColor *)backColors Font:(CGFloat )fontsize tag:(NSInteger)tags
{
    UIButton *btns = [UIButton buttonWithType:UIButtonTypeCustom];
    btns.adjustsImageWhenHighlighted = NO;
    if (![titles isEqualToString:@""] || titles != nil) {
        [btns setTitle:titles forState:UIControlStateNormal];
    }
    if (colors != nil) {
        [btns setTitleColor:colors forState:UIControlStateNormal];
    }
    if (fontsize != 0) {
        btns.titleLabel.font = [UIFont systemFontOfSize:fontsize];
    }
    if (backColors != nil) {
        btns.backgroundColor = backColors;
    }
    if (tags != -1) {
        btns.tag = tags;
    }
    return btns;
}

#pragma mark - 替代星号
+ (NSString *)replaceWithMobileNO:(NSString *)mobileStr number:(int )num numbei:(int  )nub change:(NSString *)change
{
    NSString *string = [mobileStr substringWithRange:NSMakeRange(num,nub)];
    //字符串的替换
    NSString *mobileString = [mobileStr stringByReplacingOccurrencesOfString:string withString:change];
    return mobileString;
}

#pragma mark - 跳转到下一个控制器
+ (void)ToNextName:(NSString *)nameVC Params:(id)params CurrentVC:(UIViewController *)currentVC Completion:(void (^)(id obj)) completionblock
{
    id obj = [LongriseRouter openURL:nameVC];
    if([LongriseRouter isImplLongriseRouterDelegaterWithObject:obj])
    {
        id<LongriseRouterDelegater> delegater = obj;
        if(delegater)
        {
            //进行传值，传入统一的block以供B进行回调
            [delegater setParams:params block:^(id obj) {
                
                NSLog(@"回调数据：%@",obj);
                if (completionblock) {
                    completionblock(obj);
                }
            }];
        }
    }
    if (obj && [obj isKindOfClass:[UIViewController class]]) {
        UIViewController *VC = obj;
        VC.hidesBottomBarWhenPushed = YES;
        [currentVC.navigationController pushViewController:VC animated:YES];
    }
}
#pragma mark - 判断手机号码格式是否正确

+ (BOOL)valiMobile:(NSString *)mobile
{
    mobile = [mobile stringByReplacingOccurrencesOfString:@" " withString:@""];
    if (mobile.length != 11)
    {
        return NO;
    }else{
        /**
         * 移动号段正则表达式
         */
        NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
        /**
         * 联通号段正则表达式
         */
        NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
        /**
         * 电信号段正则表达式
         */
        NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
        NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
        BOOL isMatch1 = [pred1 evaluateWithObject:mobile];
        NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
        BOOL isMatch2 = [pred2 evaluateWithObject:mobile];
        NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
        BOOL isMatch3 = [pred3 evaluateWithObject:mobile];
        
        if (isMatch1 || isMatch2 || isMatch3) {
            return YES;
        }else{
            return NO;
        }
    }
}

#pragma mark - 判断身份证号码格式是否正确
+ (BOOL)valiPenson:(NSString *)Penson{
    
    if (Penson.length != 18) return NO;
    // 正则表达式判断基本 身份证号是否满足格式
    NSString *regex = @"^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9]|X)$";
    //  NSString *regex = @"^(^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$)|(^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])((\\d{4})|\\d{3}[Xx])$)$";
    NSPredicate *identityStringPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    //如果通过该验证，说明身份证格式正确，但准确性还需计算
    if(![identityStringPredicate evaluateWithObject:Penson]) return NO;
    
    //** 开始进行校验 *//
    
    //将前17位加权因子保存在数组里
    NSArray *idCardWiArray = @[@"7", @"9", @"10", @"5", @"8", @"4", @"2", @"1", @"6", @"3", @"7", @"9", @"10", @"5", @"8", @"4", @"2"];
    
    //这是除以11后，可能产生的11位余数、验证码，也保存成数组
    NSArray *idCardYArray = @[@"1", @"0", @"10", @"9", @"8", @"7", @"6", @"5", @"4", @"3", @"2"];
    
    //用来保存前17位各自乖以加权因子后的总和
    NSInteger idCardWiSum = 0;
    for(int i = 0;i < 17;i++) {
        NSInteger subStrIndex = [[Penson substringWithRange:NSMakeRange(i, 1)] integerValue];
        NSInteger idCardWiIndex = [[idCardWiArray objectAtIndex:i] integerValue];
        idCardWiSum+= subStrIndex * idCardWiIndex;
    }
    
    //计算出校验码所在数组的位置
    NSInteger idCardMod=idCardWiSum%11;
    //得到最后一位身份证号码
    NSString *idCardLast= [Penson substringWithRange:NSMakeRange(17, 1)];
    //如果等于2，则说明校验码是10，身份证号码最后一位应该是X
    if(idCardMod==2) {
        if(![idCardLast isEqualToString:@"X"]||[idCardLast isEqualToString:@"x"]) {
            return NO;
        }
    }
    else{
        //用计算出的验证码与最后一位身份证号码匹配，如果一致，说明通过，否则是无效的身份证号码
        if(![idCardLast isEqualToString: [idCardYArray objectAtIndex:idCardMod]]) {
            return NO;
        }
    }
    return YES;
    
}


#pragma mark - 临时工具
#pragma mark - 解析头像
+ (NSString *)resolutionHeadImage:(NSString *)headimg
{
    if (!headimg.length) {
        return @"";
    }
    NSString *str = nil;
    NSArray *array = [Tools leapImgAry:[Tools toJSONData:headimg]];
    if (array.count) {
        str = [array firstObject];
    }
    else {
        str = @"";
    }
    return str;
}

+ (UIView *)creatColumView:(NSDictionary *)dict Tags:(NSInteger )tags
{
    UIView *views = [UIView new];
    UILabel *lab = [[Tools shareInstance] creat_Label:dict[@"des"] Color:[Util colorWithHexString:@"#333333"] Font:16 tag:-1 Alignment:0 Lines:1];
    UITextField *txtfields = [UITextField new];
    txtfields.font = LRFont(16);
    txtfields.placeholder = dict[@"name"];
    txtfields.borderStyle = UITextBorderStyleNone;
    txtfields.tag = tags;
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary]; // 创建属性字典
    attrs[NSFontAttributeName] = [UIFont systemFontOfSize:14]; // 设置font
    attrs[NSForegroundColorAttributeName] = [Util colorWithHexString:@"#c0c0c0"]; // 设置颜色
    NSAttributedString *attStr = [[NSAttributedString alloc] initWithString:dict[@"name"] attributes:attrs]; // 初始化富文本占位字符串
    txtfields.attributedPlaceholder = attStr;
    
    UIImageView *line = [UIImageView new];
    line.backgroundColor = K_LineColor;
    
    [views sd_addSubviews:@[lab,txtfields,line]];
    
    CGFloat left = iPhone5 == YES ? 15 : 30;
    CGFloat top = 24;
    
    lab.sd_layout
    .leftSpaceToView(views, left)
    .topSpaceToView(views, top)
    .heightIs(15);
    
    txtfields.sd_layout
    .leftSpaceToView(lab, 8)
    .rightSpaceToView(views, left)
    .centerYEqualToView(lab).offset(1)
    .heightIs(30);
    
    line.sd_layout
    .leftEqualToView(lab)
    .topSpaceToView(txtfields, 10)
    .rightEqualToView(txtfields)
    .heightIs(0.5);
    
    [lab setSingleLineAutoResizeWithMaxWidth:100];
    
    [views setupAutoHeightWithBottomView:line bottomMargin:0];
    
    return views;
}

#pragma mark - 第三方登录view
+ (UIView *)creatThirdPartyView
{
    UIView *bkView = [UIView new];
    bkView.backgroundColor = [UIColor whiteColor];
    
    NSArray *dataAry = @[@{@"title":@"微信登录",@"img":@"wx_login"},
                         @{@"title":@"QQ登录",@"img":@"QQ_login"}];
    
    UIView *noticeView = [Tools creatNoticeView];
    UIView *typeView = [Tools creatLoginTypeView:dataAry];
    [bkView sd_addSubviews:@[noticeView,typeView]];
    
    noticeView.sd_layout
    .leftSpaceToView(bkView, 0)
    .topSpaceToView(bkView, 0)
    .rightSpaceToView(bkView, 0);
    
    typeView.sd_layout
    .centerXEqualToView(bkView)
    .topSpaceToView(noticeView, 10)
    .widthIs((dataAry.count + 1) * 70);
    
    [bkView setupAutoHeightWithBottomView:typeView bottomMargin:50];
    
    return bkView;
}

+ (UIView *)creatNoticeView
{
    UIView *views = [UIView new];
    views.backgroundColor = [UIColor whiteColor];
    
    UIImageView *line = [UIImageView new];
    line.backgroundColor = K_LineColor;
    
    UIImageView *line1 = [UIImageView new];
    line1.backgroundColor = K_LineColor;
    
    UILabel *lab = [[Tools shareInstance] creat_Label:@"其他方式登录" Color:[Util colorWithHexString:@"999999"] Font:14 tag:-1 Alignment:1 Lines:1];
    
    [views sd_addSubviews:@[line,lab,line1]];
    
    lab.sd_layout
    .topSpaceToView(views, 0)
    .centerXEqualToView(views)
    .heightIs(13);
    
    line.sd_layout
    .leftSpaceToView(views, 30)
    .centerYEqualToView(lab)
    .rightSpaceToView(lab, 30)
    .heightIs(0.5);
    
    line1.sd_layout
    .leftSpaceToView(lab, 16)
    .centerYEqualToView(lab)
    .rightSpaceToView(views, 30)
    .heightIs(0.5);
    
    [lab setSingleLineAutoResizeWithMaxWidth:100];
    
    [views setupAutoHeightWithBottomView:lab bottomMargin:0];
    
    return views;
}

+ (UIView *)creatLoginTypeView:(NSArray *)array
{
    UIView *bkView = [UIView new];
    bkView.backgroundColor = [UIColor whiteColor];
    
    NSMutableArray *temp = [NSMutableArray array];
    for (int i = 0; i < array.count; i++) {
        NSDictionary *dict = array[i];
        UIView *views = [self creat_view:dict[@"img"] titles:dict[@"title"] Tag:i + 300];
        [bkView addSubview:views];
        [temp addObject:views];
        views.sd_layout.heightIs(71);
    }
    [bkView setupAutoWidthFlowItems:[temp copy] withPerRowItemsCount:array.count verticalMargin:0 horizontalMargin:50 verticalEdgeInset:0 horizontalEdgeInset:0];
    
    return bkView;
}

+ (UIView *)creat_view:(NSString *)img titles:(NSString *)titles Tag:(NSInteger)tags
{
    UIView *backViews = [UIView new];
    backViews.backgroundColor = [UIColor whiteColor];
    
    UIImageView *images = [UIImageView new];
    images.backgroundColor = [UIColor whiteColor];
    images.image = [UIImage imageNamed:img];
    
    UILabel *lab = [[Tools shareInstance] creat_Label:titles Color:[Util colorWithHexString:@"#666666"] Font:13 tag:-1 Alignment:1 Lines:1];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.backgroundColor = [UIColor clearColor];
    btn.tag = tags;
    [btn addTarget:self action:@selector(itemsClick:) forControlEvents:UIControlEventTouchUpInside];
    [backViews sd_addSubviews:@[images,lab,btn]];
    
    CGFloat width = 50;
    CGFloat height = 50;
    CGFloat margin = 9.5;
    
    images.sd_layout
    .centerXEqualToView(backViews)
    .topSpaceToView(backViews, 15)
    .widthIs(width)
    .heightIs(height);
    
    lab.sd_layout
    .topSpaceToView(images, margin)
    .centerYEqualToView(images)
    .widthRatioToView(backViews, 1)
    .heightIs(11.5);
    
    btn.sd_layout.spaceToSuperView(UIEdgeInsetsZero);
    
    return backViews;
}

+ (UIView *)creatUserView
{
    UIView *bkViews = [UIView new];
    bkViews.backgroundColor = [UIColor whiteColor];
    
    UIImageView *line = [UIImageView new];
    line.backgroundColor = K_LineColor;
    
    UIImageView *line1 = [UIImageView new];
    line1.backgroundColor = K_LineColor;
    
    UILabel *lab = [[Tools shareInstance] creat_Label:@"账号" Color:K_TitlesColor Font:15 tag:-1 Alignment:0 Lines:1];
    UITextField *txtfield = [UITextField new];
    txtfield.placeholder = @"请输入账号";
    
    UILabel *lab1 = [[Tools shareInstance] creat_Label:@"密码" Color:K_TitlesColor Font:15 tag:-1 Alignment:0 Lines:1];
    UITextField *txtfield1 = [UITextField new];
    txtfield1.placeholder = @"请输入密码";
    
    UIButton *showPWBtn = [Tools creat_Buttons:@"" Color:[UIColor blackColor] BackColors:[UIColor whiteColor] Font:16 tag:205];
    showPWBtn.frame = CGRectMake(0, 1, 30, 28);
    
    showPWBtn.tag = 30;
    [showPWBtn addTarget:self action:@selector(showTextEntry:) forControlEvents:UIControlEventTouchUpInside];
    [showPWBtn setImage:[UIImage imageNamed:@"unopen"] forState:UIControlStateNormal];
    txtfield1.secureTextEntry = YES;
    txtfield1.rightView = showPWBtn;
    txtfield1.rightViewMode = UITextFieldViewModeAlways;
   
    
    UIButton *loginBtn = [Tools creat_Buttons:@"登录" Color:[UIColor whiteColor] BackColors:KRedColors Font:18 tag:203];
    [loginBtn addTarget:self action:@selector(otherBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    LRViewRadius(loginBtn, 5, 0.5, [UIColor clearColor]);
    UIButton *desBtn = [[Tools shareInstance] creat_Button: @"使用短信验证码登录" Color:[Util colorWithHexString:@"#ff0000"] BackColors:[UIColor whiteColor] Font:14 tag:204];
    [desBtn addTarget:self action:@selector(otherBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    [bkViews sd_addSubviews:@[lab,txtfield,lab1,txtfield1,loginBtn,desBtn]];
    
    CGFloat left = iPhone5 == YES ? 15 : 30;
    
    lab.sd_layout
    .leftSpaceToView(bkViews, left)
    .topSpaceToView(bkViews, left)
    .widthIs(100)
    .heightIs(25);
    
    txtfield.sd_layout
    .leftSpaceToView(lab, 10)
    .centerYEqualToView(lab)
    .rightSpaceToView(bkViews, left)
    .heightIs(30);
    
    lab1.sd_layout
    .leftEqualToView(lab)
    .topSpaceToView(lab, left)
    .widthRatioToView(lab, 1)
    .heightRatioToView(lab, 1);
    
    txtfield1.sd_layout
    .leftEqualToView(txtfield)
    .centerYEqualToView(lab1)
    .rightEqualToView(txtfield)
    .heightRatioToView(txtfield, 1);
    
    loginBtn.sd_layout
    .leftSpaceToView(bkViews, left)
    .topSpaceToView(txtfield1, 20)
    .rightSpaceToView(bkViews, left)
    .heightIs(45);

    desBtn.sd_layout
    .topSpaceToView(loginBtn, 20)
    .leftEqualToView(loginBtn)
    .rightEqualToView(loginBtn)
    .heightIs(40);
    [bkViews setupAutoHeightWithBottomView:desBtn bottomMargin:0];
    return bkViews;
}
#pragma mark - 字典通过plist文件存本地
+ (void)Dictionariesplistname:(NSMutableArray *)pname {
    
   
    
    // NSDocumentDirectory 要查找的文件
    // NSUserDomainMask 代表从用户文件夹下找
    // 在iOS中，只有一个目录跟传入的参数匹配，所以这个集合里面只有一个元素
    NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSString *filePath = [path stringByAppendingPathComponent:@"policy.plist"];
    [pname writeToFile:filePath atomically:YES];
}
#pragma mark - 定期更新一下用户信息
+ (void)updatepreson{
    
    NSMutableDictionary *bean = [NSMutableDictionary dictionary];
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [bean setValue:dict forKey:@"entitybean"];
    [dict setObject:[Globle getInstance].account.userid.length > 0 ? [Globle getInstance].account.userid : @"" forKey:@"id"];
//    NSString *str = [NSString string];
//    if ([[Globle getInstance].account.sex isEqualToString:@"1"]){
//        str = @"男";
//    }else if ([[Globle getInstance].account.sex isEqualToString:@"2"]){
//        str = @"女";
//    }else{
//        str = @"";
//    }
//    [dict setObject:str forKey:@"sex"];
    [NetRequestClass Post:UpdateUserInfoURL Parameters:bean success:^(id result) {
       
        [[Globle getInstance] saveAccountInfo:result[@"data"]];
       
    } failure:^(id valueCode, id error) {
        
    }];
}

+ (UIView *)creatPhoneView
{
    UIView *backViews = [UIView new];
    backViews.backgroundColor = [UIColor whiteColor];
    UIImageView *images = [UIImageView new];
    images.backgroundColor = [UIColor redColor];
    images.image = [UIImage imageNamed:@""];
    
    UILabel *lab = [[Tools shareInstance] creat_Label:@"测试手机" Color:[Util colorWithHexString:@"#666666"] Font:13 tag:-1 Alignment:1 Lines:1];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.backgroundColor = [UIColor clearColor];
//        btn.tag = tags;
    [btn addTarget:self action:@selector(itemsClick:) forControlEvents:UIControlEventTouchUpInside];
    [backViews sd_addSubviews:@[images,lab,btn]];
    
    CGFloat width = 50;
    CGFloat height = 50;
    CGFloat margin = 9.5;
    
    images.sd_layout
    .centerXEqualToView(backViews)
    .topSpaceToView(backViews, 15)
    .widthIs(width)
    .heightIs(height);
    
    lab.sd_layout
    .topSpaceToView(images, margin)
    .centerYEqualToView(images)
    .widthRatioToView(backViews, 1)
    .heightIs(11.5);
    
    btn.sd_layout.spaceToSuperView(UIEdgeInsetsZero);
    return backViews;
}
@end
